const { User, UserInfo } = require("../model/connect");

const router = require("koa-router")();
const jwt = require("jsonwebtoken");
const koaJWT = require("koa-jwt");
const secret = "hello world";

router.post("/register", async (ctx) => {
    const { username, password } = ctx.request.body;
    console.log(username, password);
    if (!username || !password) {
        ctx.status = 400;
        ctx.body = {
            code: 400,
            message: "用户名或密码不能为空",
        };
        return;
    }
    try {
        let user = await User.findOne({ where: { username } });
        if (user) {
            ctx.status = 400;
            ctx.body = {
                code: 400,
                message: "用户名已存在",
            };
            return;
        }
        let newUser = await User.create({ username, password });
        await UserInfo.create({
            nikename: newUser.username,
            desc: "这个人很懒，什么也没留下",
            gender: 1,
            UserId: newUser.id,
        });
        ctx.status = 200;
        ctx.body = {
            code: 200,
            message: newUser,
        };
    } catch (e) {
        ctx.status = 500;
        ctx.body = {
            code: 500,
            message: e.message,
        };
    }
});
router.post("/login", async (ctx) => {
    const { username, password } = ctx.request.body;
    if (!username || !password) {
        ctx.status = 400;
        ctx.body = {
            message: "用户名或密码不能为空",
        };
        return;
    }
    try {
        let user = await User.findOne({ where: { username, password } });
        if (!user) {
            ctx.status = 400;
            ctx.body = {
                code: 400,
                message: "用户名或密码错误",
            };
            return;
        }
        let token = jwt.sign({ username }, secret, { expiresIn: "2h" });
        ctx.status = 200;
        ctx.body = {
            code: 200,
            message: "登陆成功",
            data: {
                user,
                token,
            },
        };
    } catch (e) {
        ctx.status = 500;
        ctx.body = {
            code: 500,
            message: e.message,
        };
    }
});
router.get("/userInfos", koaJWT({ secret }), async (ctx) => {
    let userinfos = await UserInfo.findAll({});
    ctx.status = 200;
    ctx.body = {
        code: 200,
        message: "查询全部信息成功",
        data: userinfos,
    };
});

router.delete("/user/:id", async (ctx) => {
    const { id } = ctx.params;
    await User.destroy({ where: { id } });
    ctx.status = 200;
    ctx.body = {
        code: 200,
        message: "删除用户和用户信息成功",
    };
});

module.exports = router;
